<?php

require_once '../mysqlConnect.php';
$files = glob("../Model/*.php");
foreach ($files as $file)
	require_once "$file";


class PatientFile {
	
	public $conn;
	public static $fileFolder = "PatientFiles";
	public static $protocol = "http://";
	public static $hostname = "www2.newpaltz.edu/~N01350819/Psychology";
	#public static $hostname = "localhost";
	
	function __autoload($class_name) {
		include $class_name . ".php";
	}
	
	function __construct($conn) {
		$this->conn = $conn;
	}
	
	#Patient
	function getPatientInformation($patId) {
		
		$sql = "SELECT * FROM Patient WHERE ID = :id";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Patient");
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results= $STH->fetch();
			return $results;
		} catch(PDOException $e) {  
	    	return null;
		}
	}
	
	
	#medical_test_answers, medical_test_questions
	function getPatientMedicationRecords ($patId) {
		
		$sql = "SELECT * FROM medical_test_answers WHERE patient_id = :id ORDER BY record_date desc";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Medical_Test_Answer");
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	function getPatientMedicationQuestions () {
	
		$sql = "SELECT * FROM medical_test_questions";
	
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Medical_Test_Question");
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	#Test
	function getMedicalTestName ($testId) {
		
		$sql = "SELECT * FROM Test WHERE ID = :id";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->bindValue(":id", $testId);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Medication");
			$STH->execute();
			$results = $STH->fetch();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}	
	}
	
	
	#prescription_records, prescription_questions
	function getPatientPrescriptionRecords ($patId) {
	
		$sql = "SELECT * FROM prescription_records WHERE patient_id = :id ORDER BY start_date desc";
	
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Prescription_Record");
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	function getPrescriptionQuestions () {
		
		$sql = "SELECT * FROM prescription_questions";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Prescription_Question");
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}		
	}
	
	
	#Medication
	function getMedication($medId) {
		
		$sql = "SELECT * FROM Medication WHERE ID = :id";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Medication");
			$STH->bindValue(":id", $medId);
			$STH->execute();
			$results = $STH->fetch();
			return $results;
		} catch (PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	#psychological_test_answers, psychological_test_questions
	function getPsychologicalAnswers ($patId) {

		$sql = "SELECT * FROM psychological_test_answers WHERE patient_id = :id ORDER BY record_date desc";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Psychological_Test_Answer");
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	function getPsychologicalQuestions () {
		
		$sql = "SELECT * FROM psychological_test_questions";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Psychological_Test_Question");
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	#physical_symptom_answers, physical_symptom_questions
	function getPhysicalAnswers ($patId) {
		
		$sql = "SELECT * FROM physical_symptom_answers WHERE patient_id = :id ORDER BY record_date desc";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Physical_Symptom_Answer");
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	function getPhysicalQuestions () {
	
		$sql = "SELECT * FROM physical_symptom_questions";
	
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Physical_Symptom_Question");
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	
	#neuropsychological_symptom_answers, neuropsychological_symptom_questions
	function getNeuroPsychologicalAnswers ($patId) {
		
		$sql = "SELECT * FROM neuropsychological_symptom_answers WHERE patient_id = :id ORDER BY record_date desc";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Neuropsychological_Symptom_Answer");
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	function getNeuroPsychologicalQuestions () {
		
		$sql = "SELECT * FROM neuropsychological_symptom_questions";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Neuropsychological_Symptom_Question");
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	function getICD9Records($patId) {
		
		$sql = "SELECT icd_nine_entry.*, icd_codes.id as icd_id, icd_codes.code, icd_codes.name FROM icd_nine_entry JOIN icd_codes ON icd_nine_entry.code_id = icd_codes.id WHERE patient_id = :id ORDER BY date_given DESC";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_ASSOC);
			$STH->bindValue(":id", $patId);
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	function getAnswerOptions () {
		
		$sql = "SELECT * FROM answer_options";
		
		try {
			$STH = $this->conn->prepare($sql);
			$STH->setFetchMode(PDO::FETCH_CLASS, "Answer_Option");
			$STH->execute();
			$results = $STH->fetchAll();
			return $results;
		} catch(PDOException $e) {
			return $e->getMessage();
		}
	}
	
	
	function listPatientFiles ($patId) {
		
		$patientInfo = $this->getPatientInformation($patId);
		$patientVariables = $patientInfo->get();
		if (!is_dir("../" . self::$fileFolder))
			return "No Files Exist";
		elseif (!is_dir("../" . self::$fileFolder . "/" . $patientVariables['PatID']))
			return "No Files Exist";
		else {
			$files = scandir("../" . self::$fileFolder . "/" . $patientVariables['PatID']);
			unset($files[0]);
			unset($files[1]);
			if (count($files) < 1)
				return "No Files Exist";
			
			rsort($files);
			$returnArray = array();
			foreach ($files as $key => $file)
				$returnArray[$file] = self::$protocol . self::$hostname . "/" . self::$fileFolder . "/" . $patientVariables['PatID'] . "/" . $file;
			
			return $returnArray;
		}
	}
}












function savePatientInfo($patId) {
	
	
	$PatientFile = new PatientFile(GetPDOConnection());
	$patient = $PatientFile->getPatientInformation($patId);
	$patientVariables = $patient->get();
	$delim = "|";
	
	# create directories, create file handle
	{
		if (count($patientVariables) < 1) {
			return "fail".$delim."Unable to retrieve patient information";
			exit();
		}
	
		if (!is_dir("../{$PatientFile::$fileFolder}/")) {
			if (!mkdir("../{$PatientFile::$fileFolder}/", 0777, true)) { # TODO
				return "fail".$delim."No file folder present and unable to create one";
				exit();
			} else
				chmod("../{$PatientFile::$fileFolder}/", 0777);
		}
		if (!is_dir("../{$PatientFile::$fileFolder}/$patientVariables[PatID]")) {
			if (!mkdir("../{$PatientFile::$fileFolder}/$patientVariables[PatID]", 0777, true)) { # TODO
				return "fail".$delim."Unable to create patient folder";
				exit();
			} else
				chmod("../{$PatientFile::$fileFolder}/$patientVariables[PatID]", 0777);
		}
	
		date_default_timezone_set("America/New_York");
		$date = date("Y-m-d");
		
		$FH = fopen("../{$PatientFile::$fileFolder}/$patientVariables[PatID]/$patientVariables[PatID]_$date.csv", "w");
		chmod("../{$PatientFile::$fileFolder}/$patientVariables[PatID]/$patientVariables[PatID]_$date.csv", 0777);
	}
	
	
	# basic patient information
	fputcsv($FH, array($patientVariables['PatID'], $date), $delim);
	fputcsv($FH, array("BASIC PATIENT INFORMATION"), $delim);
	
	$fields = array(
					"Patient ID" => $patientVariables['PatID'],
					"DOB" => $patientVariables['DOB'],
					"Gender" => $patientVariables['Gender'],
					"Relationship Status" => $patientVariables['RelationshipStatus'] == 1 ? "In a Relationship" : "Single",
					"Occupation Status" => $patientVariables['RelationshipStatus'] == 1 ? "Employed" : "Unemployed",
					"Ticks in Work Habitat" => $patientVariables['WorkHabitat'] == 1 ? "Yes" : "No",
					"Ticks in Hunting Habitat" => $patientVariables['HuntHabitat'] == 1 ? "Yes" : "No",
					"Ticks in Play Habitat" => $patientVariables['PlayHabitat'] == 1 ? "Yes" : "No",
					"Ticks in Gardening Habitat" => $patientVariables['GardenHabitat'] == 1 ? "Yes" : "No",
					"Tickbite Caused Disease" => $patientVariables['TickBite'] == 1 ? "Yes" : "No",
					"Has a Rash" => $patientVariables['Rash'] == 1 ? "Yes" : "No",
					"Date Diagnosed" => $patientVariables['DateDiagnosed']
	);
	
	fputcsv($FH, array_keys($fields), $delim);
	fputcsv($FH, array_values($fields), $delim);
	
	
	
	#TCD9 Records TODO
	{
		fputcsv($FH, array());
		fputcsv($FH, array("ICD9 INFORMATION"));
		$icd_nine_entries = $PatientFile->getICD9Records($patientVariables['ID']);
		
		if (count($icd_nine_entries) < 1)
			fputcsv($FH, array("NO INFORMATION FOUND IN DATABASE"));
		else {
						
			fputcsv($FH, array("Code", "Name", "Date Assigned"), $delim);
			foreach ($icd_nine_entries as $key => $icd_nineObject) {
				
				fputcsv($FH, array($icd_nineObject['code'], $icd_nineObject['name'], $icd_nineObject['date_given']), $delim);
			}
		}
	}
	
	
	
	# medication records
	{
		fputcsv($FH, array());
		fputcsv($FH, array("MEDICATION INFORMATION"));
		$medications = $PatientFile->getPatientMedicationRecords($patientVariables['ID']);
		
		if (count($medications) < 1)
			fputcsv($FH, array("NO INFORMATION FOUND IN DATABASE"));
		else {
			
			$medicalQuestions = $PatientFile->getPatientMedicationQuestions();
			$fields = array();
			foreach ($medicalQuestions as $question) {
				$medicationQuestions = $question->get();
				$fields[] = $medicationQuestions['text'];
			}
			fputcsv($FH, $fields, $delim);
			
			foreach ($medications as $medicationObject) {
				$medicationVariables = $medicationObject->get();
				$medName = $PatientFile->getMedicalTestName($medicationVariables['testname']);
				$Name = $medName->get();
				fputcsv($FH, array($Name['Name'], $medicationVariables['result1'], $medicationVariables['result2'], $medicationVariables['record_date']), $delim);
			}
		}
	}
	
	
	# prescription information
	{
		fputcsv($FH, array());
		fputcsv($FH, array("PRESCRIPTION INFORMATION"));
		$prescription_records = $PatientFile->getPatientPrescriptionRecords ($patientVariables['ID'] );
		
		if (count($prescription_records) < 1)
			fputcsv($FH, array("NO INFORMATION FOUND IN DATABASE"));
		else {
			
			$prescriptionQuestions = $PatientFile->getPrescriptionQuestions();
			$fields = array();
			foreach ($prescriptionQuestions as $question) {
				$presQuestion = $question->get();
				$fields[] = $presQuestion['text'];
			}
			fputcsv($FH, $fields, $delim);
			
			foreach ($prescription_records as $prescriptionObject) {
				$prescriptionVariables = $prescriptionObject->get();
				$medName = $PatientFile->getMedication($prescriptionVariables['medication_id']);
				$name = $medName->get();
				fputcsv($FH, array($name['Name'], $prescriptionVariables['dosage'] . "mg", $prescriptionVariables['start_date'], $prescriptionVariables['end_date']), $delim);
			}
		}
	}
	
	# answer options
	{
		$answerOptionObjects = $PatientFile->getAnswerOptions ();
		foreach ($answerOptionObjects as $object) {
			$objectVariables = $object->get();
			$answerOptions[$objectVariables['type']] = $objectVariables['description'];
		}
	}
	
	
	#psychological test information
	{
		fputcsv($FH, array());
		fputcsv($FH, array("PSYCHOLOGICAL TEST INFORMATION"));
		$psychological_test_answers = $PatientFile->getPsychologicalAnswers($patientVariables['ID']);
		
		if (count($psychological_test_answers) < 1)
			fputcsv($FH, array("NO INFORMATION FOUND IN DATABASE"));
		else {
			
			$psychologicalQuestions = $PatientFile->getPsychologicalQuestions();
			$fields = array();
			foreach ($psychologicalQuestions as $question) {
				$psychQuestion = $question->get();
				$fields[] = $psychQuestion['text'];
			}
			fputcsv($FH, $fields, $delim);
			
			foreach ($psychological_test_answers as $psychologicalAnswerObject) {
				$psychologicalVariables = $psychologicalAnswerObject->get();
				fputcsv($FH, array($psychologicalVariables['qnumber1'] . " : " . $answerOptions[$psychologicalVariables['qnumber1']], $psychologicalVariables['qnumber2']  . " : " . $answerOptions[$psychologicalVariables['qnumber2']], $psychologicalVariables['qnumber3'], $psychologicalVariables['global'], $psychologicalVariables['record_date']), $delim);
			}
		}
	}
	
	
	#physical symptom information
	{
		fputcsv($FH, array());
		fputcsv($FH, array("PHYSICAL SYMPTOM INFORMATION"));
		$physical_symptom_answers = $PatientFile->getPhysicalAnswers($patientVariables['ID']);
		
		if (count($physical_symptom_answers) < 1)
			fputcsv($FH, array("NO INFORMATION FOUND IN DATABASE"));
		else {
			
			$physicalQuestions = $PatientFile->getPhysicalQuestions();
			$fields = array();
			foreach ($physicalQuestions as $question) {
				$physQuestion = $question->get();
				$fields[] = $physQuestion['text'];
			}
			fputcsv($FH, $fields, $delim);
			
			foreach ($physical_symptom_answers as $physicalSymptomAnswerObject) {
				$physicalVariables = $physicalSymptomAnswerObject->get();
				fputcsv($FH, array(
						$physicalVariables['qnumber1'],
						$physicalVariables['qnumber2'],
						$physicalVariables['qnumber3'],
						$physicalVariables['qnumber4'],
						$physicalVariables['qnumber5'],
						$physicalVariables['qnumber6'],
						$physicalVariables['qnumber7'],
						$physicalVariables['qnumber8'],
						$physicalVariables['qnumber9'],
						$physicalVariables['qnumber10'],
						$physicalVariables['qnumber11'],
						$physicalVariables['qnumber12'],
						$physicalVariables['qnumber13'],
						$physicalVariables['qnumber14'],
						$physicalVariables['qnumber15'],
						$physicalVariables['qnumber16'],
						$physicalVariables['qnumber17'],
						$physicalVariables['record_date']
				), $delim);
			}
		}
	}
	
	
	#neuropsychological symptom information
	{
		fputcsv($FH, array());
		fputcsv($FH, array("NEUROPSYCHOLOGICAL SYMPTOM INFORMATION"));
		$neuropsychological_symptom_answers = $PatientFile->getNeuroPsychologicalAnswers($patientVariables['ID']);
		
		if (count($neuropsychological_symptom_answers) < 1)
			fputcsv($FH, array("NO INFORMATION FOUND IN DATABASE", $delim));
		else {
			
			$neuroPsychQuestions = $PatientFile->getNeuroPsychologicalQuestions();
			$fields = array();
			foreach ($neuroPsychQuestions as $question) {
				$neuroPsychQuestion = $question->get();
				$fields[] = $neuroPsychQuestion['text'];
			}
			fputcsv($FH, $fields, $delim);
			
			foreach ($neuropsychological_symptom_answers as $neuroPsychologicalSymptomAnswerObject) {
				$neuroPsychVariables = $neuroPsychologicalSymptomAnswerObject->get();
				fputcsv($FH, array(
						$neuroPsychVariables['qnumber1'],
						$neuroPsychVariables['qnumber2'],
						$neuroPsychVariables['qnumber3'],
						$neuroPsychVariables['qnumber4'],
						$neuroPsychVariables['qnumber5'],
						$neuroPsychVariables['qnumber6'],
						$neuroPsychVariables['qnumber7'],
						$neuroPsychVariables['qnumber8'],
						$neuroPsychVariables['qnumber9'],
						$neuroPsychVariables['record_date']
				), $delim);
			}
		}
	}
	
	fclose($FH);
	
	return 'success'.$delim.'<a href="' . $PatientFile::$protocol . $PatientFile::$hostname . '/' . $PatientFile::$fileFolder . '/' . $patientVariables['PatID'] . '/' . $patientVariables['PatID'] . '_' . $date . '.csv">Open File</a>';

}

function listPatientFiles($patId) {
	
	$object = new PatientFile(GetPDOConnection());
	return $object->listPatientFiles($patId);
}

function deletePatientFiles($fileURL) {
	
	$urlParts = parse_url($fileURL);
	$parts = explode("/", $urlParts['path']);
	
	if (unlink("../" . $parts[count($parts) - 3] . "/" .$parts[count($parts) - 2] . "/" . $parts[count($parts) - 1]))
		return 0;
	else
		return "../" . $parts[count($parts) - 3] . "/" .$parts[count($parts) - 2] . "/" . $parts[count($parts) - 1];
}

if (isset($_POST) && isset($_POST['PatId']) && isset($_POST['method'])) {
	
	if ($_POST['method'] == "listPatientFiles") {
		
		$patientFiles = listPatientFiles($_POST['PatId']);
				
		if ($patientFiles == "No Files Exist")
			echo $patientFiles;
		else {
			$returnString = "<table style='margin: auto; width: 90%;'>";
			foreach ($patientFiles as $fileName => $fileLocation) {
				
				$file_parts1 = explode("_", $fileName);
				$file_parts2 = explode(".", $file_parts1[1]);
				$dateText = $file_parts2[0];

				$returnString .= "<tr id='$dateText'>";
					$returnString .= "<td style='text-align: left;'>";
						$returnString .= "<a href='$fileLocation'>$dateText</a>";
					$returnString .= "</td>";				
					$returnString .= "<td style='margin-left: 20px;'>";
						$returnString .= "<a href='javascript:deleteFile(\"$dateText|$fileLocation\")' style='padding-left: 10px;'>";
							$returnString .= "<img src='../Images/trash.png' width='25'>";
						$returnString .= "</a>";
					$returnString .= "</td>";
				$returnString .= "</tr>";
			}
			$returnString .= "</table>";
			echo $returnString;
		}
	}
	elseif ($_POST['method'] == "savePatientFile")
		echo savePatientInfo($_POST['PatId']);
	elseif ($_POST['method'] == "deletePatientFile") {
		
		if (!isset($_POST['fileURL']))
			echo "error: missing file URL";
		elseif (!isset($_POST['divID']))
			echo "error: missing div id";
		else {
			$attempt = deletePatientFiles($_POST['fileURL']);
			if ($attempt === 0) {
				echo "success|$_POST[divID]";
			} else 
				echo "fail|$attempt";
		}
	}
	else 
		echo "Malformed URL";
		
}
